<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>授权获取 Cookie 测试页</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 900px;
      margin: 40px auto;
      padding: 24px;
      background: #f7f8fa;
      color: #333;
    }
    h1 {
      margin-bottom: 24px;
      font-size: 26px;
      text-align: center;
    }
    .card {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      padding: 24px;
      margin-bottom: 24px;
    }
    .card h2 {
      margin-top: 0;
      font-size: 20px;
      margin-bottom: 16px;
    }
    .form-group {
      margin-bottom: 16px;
    }
    label {
      display: block;
      font-weight: bold;
      margin-bottom: 6px;
      color: #555;
    }
    input, textarea {
      width: 100%;
      padding: 10px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      font-size: 14px;
      box-sizing: border-box;
    }
    textarea {
      font-family: monospace;
      resize: vertical;
      min-height: 120px;
    }
    button {
      background: #409eff;
      color: #fff;
      border: none;
      border-radius: 4px;
      padding: 10px 18px;
      font-size: 15px;
      cursor: pointer;
      margin-right: 10px;
    }
    button.secondary {
      background: #67c23a;
    }
    button:disabled {
      background: #c0c4cc;
      cursor: not-allowed;
    }
    .tips {
      background: #fffbe6;
      border: 1px solid #ffe58f;
      padding: 16px;
      border-radius: 6px;
      margin-bottom: 18px;
      color: #ad8b00;
    }
    .result {
      margin-top: 14px;
      padding: 14px;
      border-radius: 4px;
      display: none;
      white-space: pre-wrap;
      word-break: break-all;
    }
    .result.success {
      display: block;
      background: #f0f9ff;
      border: 1px solid #67c1ff;
      color: #2b85e4;
    }
    .result.error {
      display: block;
      background: #fef0f0;
      border: 1px solid #f56c6c;
      color: #c45656;
    }
    .cookie-output {
      margin-top: 10px;
      padding: 12px;
      border-radius: 4px;
      background: #fafafa;
      border: 1px solid #ebeef5;
      font-family: monospace;
      white-space: pre-wrap;
      word-break: break-all;
    }
    .section-title {
      font-size: 18px;
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .section-title span {
      font-size: 13px;
      color: #909399;
    }
  </style>
</head>
<body>
  <h1>授权获取 Cookie 测试页</h1>

  <div class="card">
    <div class="tips">
      <strong>使用说明</strong>
      <ul style="margin: 8px 0; padding-left: 20px;">
        <li>确保桌面端程序已启动并允许通过 8888 端口通信</li>
        <li>点击「授权」按钮后，桌面端会打开对应平台的授权标签页，请在 3 分钟内完成登录</li>
        <li>登录成功后会弹出 “授权店群成功” 提示，并自动关闭授权标签页</li>
        <li>返回的 Cookie 会自动填入下方的 “一键登录” 测试区域</li>
      </ul>
    </div>

    <div id="authCards">
      <div class="auth-section">
        <div class="section-title">
          <strong>美团外卖授权</strong>
        </div>
        <button id="authorizeMeituanBtn" onclick="authorize('meituan')">美团外卖授权</button>
        <div id="authResult-meituan" class="result"></div>
        <div class="form-group cookie-wrapper" id="cookieContainer-meituan" style="display: none;">
          <label>授权返回的 Cookie：</label>
          <div id="cookieOutput-meituan" class="cookie-output"></div>
        </div>
      </div>

      <div class="auth-section">
        <div class="section-title">
          <strong>饿了么外卖授权</strong>
        </div>
        <button id="authorizeElemeBtn" onclick="authorize('eleme')">饿了么外卖授权</button>
        <div id="authResult-eleme" class="result"></div>
        <div class="form-group cookie-wrapper" id="cookieContainer-eleme" style="display: none;">
          <label>授权返回的 Cookie：</label>
          <div id="cookieOutput-eleme" class="cookie-output"></div>
        </div>
      </div>

      <div class="auth-section">
        <div class="section-title">
          <strong>饿百零售授权</strong>
        </div>
        <button id="authorizeElemeRetailBtn" onclick="authorize('elemeRetail')">饿百零售授权</button>
        <div id="authResult-elemeRetail" class="result"></div>
        <div class="form-group cookie-wrapper" id="cookieContainer-elemeRetail" style="display: none;">
          <label>授权返回的 Cookie：</label>
          <div id="cookieOutput-elemeRetail" class="cookie-output"></div>
        </div>
      </div>

      <div class="auth-section">
        <div class="section-title">
          <strong>京东到家授权</strong>
        </div>
        <button id="authorizeJdBtn" onclick="authorize('jd')">京东到家授权</button>
        <div id="authResult-jd" class="result"></div>
        <div class="form-group cookie-wrapper" id="cookieContainer-jd" style="display: none;">
          <label>授权返回的 Cookie：</label>
          <div id="cookieOutput-jd" class="cookie-output"></div>
        </div>
      </div>

      <div class="auth-section">
        <div class="section-title">
          <strong>抖店授权</strong>
        </div>
        <button id="authorizeDoudianBtn" onclick="authorize('doudian')">抖店授权</button>
        <div id="authResult-doudian" class="result"></div>
        <div class="form-group cookie-wrapper" id="cookieContainer-doudian" style="display: none;">
          <label>授权返回的 Cookie：</label>
          <div id="cookieOutput-doudian" class="cookie-output"></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
    <h2>一键登录测试</h2>

    <div class="form-group">
      <label>美团外卖登录 Cookie</label>
      <textarea id="loginCookies-meituan" placeholder="等待授权结果后自动填入"></textarea>
    </div>
    <button id="loginMeituanBtn" class="secondary" onclick="login('meituan')" disabled>美团外卖一键登录</button>
    <div id="loginResult-meituan" class="result"></div>

    <hr style="margin: 24px 0; border: none; border-top: 1px solid #ebeef5;">

    <div class="form-group">
      <label>饿了么外卖登录 Cookie</label>
      <textarea id="loginCookies-eleme" placeholder="等待授权结果后自动填入"></textarea>
    </div>
    <button id="loginElemeBtn" class="secondary" onclick="login('eleme')" disabled>饿了么外卖一键登录</button>
    <div id="loginResult-eleme" class="result"></div>

    <hr style="margin: 24px 0; border: none; border-top: 1px solid #ebeef5;">

    <div class="form-group">
      <label>饿百零售登录 Cookie</label>
      <textarea id="loginCookies-elemeRetail" placeholder="等待授权结果后自动填入"></textarea>
    </div>
    <button id="loginElemeRetailBtn" class="secondary" onclick="login('elemeRetail')" disabled>饿百零售一键登录</button>
    <div id="loginResult-elemeRetail" class="result"></div>

    <hr style="margin: 24px 0; border: none; border-top: 1px solid #ebeef5;">

    <div class="form-group">
      <label>京东到家登录 Cookie</label>
      <textarea id="loginCookies-jd" placeholder="等待授权结果后自动填入"></textarea>
    </div>
    <button id="loginJdBtn" class="secondary" onclick="login('jd')" disabled>京东到家一键登录</button>
    <div id="loginResult-jd" class="result"></div>

    <hr style="margin: 24px 0; border: none; border-top: 1px solid #ebeef5;">

    <div class="form-group">
      <label>抖店登录 Cookie</label>
      <textarea id="loginCookies-doudian" placeholder="等待授权结果后自动填入"></textarea>
    </div>
    <button id="loginDoudianBtn" class="secondary" onclick="login('doudian')" disabled>抖店一键登录</button>
    <div id="loginResult-doudian" class="result"></div>
  </div>

  <script>
    const ELECTRON_COMM_URL = 'http://127.0.0.1:8888'
    const lastAuthorizedCookies = {
      meituan: '',
      eleme: '',
      elemeRetail: '',
      jd: '',
      doudian: ''
    }

    const AUTH_CONFIGS = {
      meituan: {
        loginUrl: 'https://e.waimai.meituan.com/',
        cookieDomain: 'e.waimai.meituan.com',
        loginKeyword: 'wmPoiId',
        timeoutSeconds: 180
      },
      eleme: {
        loginUrl: 'https://melody.shop.ele.me/login',
        cookieDomain: 'melody.shop.ele.me',
        loginKeyword: 'ksid',
        timeoutSeconds: 180
      },
      elemeRetail: {
        loginUrl: 'https://nr.ele.me/eleme-nr-bfe-newretail/eb_login',
        cookieDomain: 'nr.ele.me',
        loginKeyword: 'WMSTOKEN=',
        timeoutSeconds: 180
      },
      jd: {
        loginUrl: 'https://store.jddj.com/base/login',
        cookieDomain: 'store.jddj.com',
        loginKeyword: 'store_session',
        timeoutSeconds: 180
      },
      doudian: {
        loginUrl: 'https://fxg.jinritemai.com/login/common',
        cookieDomain: 'jsls.jinritemai.com',
        loginKeyword: 'csrf_session_id',
        timeoutSeconds: 180
      }
    }

    const LOGIN_CONFIGS = {
      meituan: {
        url: 'https://e.waimai.meituan.com/',
        shopId: 'wm_authorization_demo',
        shopName: '美团外卖授权测试'
      },
      eleme: {
        url: 'https://melody.shop.ele.me/',
        shopId: 'eleme_authorization_demo',
        shopName: '饿了么外卖授权测试'
      },
      elemeRetail: {
        url: 'https://nr.ele.me/',
        shopId: 'eleme_retail_authorization_demo',
        shopName: '饿百零售授权测试'
      },
      jd: {
        url: 'https://store.jddj.com/',
        shopId: 'jd_authorization_demo',
        shopName: '京东到家授权测试'
      },
      doudian: {
        url: 'https://jsls.jinritemai.com/',
        shopId: 'doudian_authorization_demo',
        shopName: '抖店授权测试'
      }
    }

    function showMessage(elementId, message, isError = false) {
      const el = document.getElementById(elementId)
      el.className = `result ${isError ? 'error' : 'success'}`
      el.textContent = message
    }

    async function postToElectron(payload) {
      const response = await fetch(ELECTRON_COMM_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      return response.json()
    }

    async function authorize(platform) {
      const config = AUTH_CONFIGS[platform]
      if (!config) return

      const authResultId = `authResult-${platform}`
      const cookieContainerId = `cookieContainer-${platform}`
      const cookieOutputId = `cookieOutput-${platform}`

      const authorizeBtnIdMap = {
        meituan: 'authorizeMeituanBtn',
        eleme: 'authorizeElemeBtn',
        elemeRetail: 'authorizeElemeRetailBtn',
        jd: 'authorizeJdBtn',
        doudian: 'authorizeDoudianBtn'
      }
      const loginBtnIdMap = {
        meituan: 'loginMeituanBtn',
        eleme: 'loginElemeBtn',
        elemeRetail: 'loginElemeRetailBtn',
        jd: 'loginJdBtn',
        doudian: 'loginDoudianBtn'
      }

      const authorizeBtnId = authorizeBtnIdMap[platform]
      const loginBtnId = loginBtnIdMap[platform]

      const btn = document.getElementById(authorizeBtnId)
      const loginBtn = document.getElementById(loginBtnId)
      btn.disabled = true
      loginBtn.disabled = true
      showMessage(authResultId, '开始执行授权，请在桌面端完成登录...', false)
      document.getElementById(cookieContainerId).style.display = 'none'

      try {
        const payload = { action: 'authorize', ...config }

        const result = await postToElectron(payload)

        if (result.success) {
          lastAuthorizedCookies[platform] = result.cookies || ''
          const loginInput = document.getElementById(`loginCookies-${platform}`)
          if (loginInput) {
            loginInput.value = lastAuthorizedCookies[platform]
          }

          const cookieDiv = document.getElementById(cookieOutputId)
          cookieDiv.textContent = lastAuthorizedCookies[platform] || '(未返回 Cookie)'
          document.getElementById(cookieContainerId).style.display = 'block'
          showMessage(authResultId, `授权成功，Cookie 域名：${result.cookieDomain || config.cookieDomain}`, false)
          if (lastAuthorizedCookies[platform]) {
            loginBtn.disabled = false
          }
        } else {
          const code = result.errorCode ? `[${result.errorCode}] ` : ''
          showMessage(authResultId, `${code}${result.message || '授权失败'}`, true)
        }
      } catch (error) {
        showMessage(authResultId, `授权请求失败：${error.message}`, true)
      } finally {
        btn.disabled = false
      }
    }

    async function login(platform) {
      const loginConfig = LOGIN_CONFIGS[platform]
      if (!loginConfig) return

      const cookies = document.getElementById(`loginCookies-${platform}`).value.trim()

      if (!cookies) {
        showMessage(`loginResult-${platform}`, '当前没有授权得到的 Cookie', true)
        return
      }

      try {
        const result = await postToElectron({
          ...loginConfig,
          cookies: cookies || undefined
        })

        if (result.success) {
          showMessage(`loginResult-${platform}`, `一键登录成功（${result.action || 'open'}）`, false)
        } else {
          showMessage(`loginResult-${platform}`, `登录失败：${result.message}`, true)
        }
      } catch (error) {
        showMessage(`loginResult-${platform}`, `发送登录指令失败：${error.message}`, true)
      }
    }
  </script>
</body>
</html>

